#!/usr/bin/env bash
set -e

# Load configs
CONFIG_FILE=%%HASSIO_CONFIG%%

SUPERVISOR="$(jq --raw-output '.supervisor' ${CONFIG_FILE})"
MACHINE="$(jq --raw-output '.machine' ${CONFIG_FILE})"
DATA="$(jq --raw-output '.data // "/usr/share/hassio"' ${CONFIG_FILE})"

# AppArmor Support
if command -v apparmor_parser > /dev/null 2>&1 && grep hassio-supervisor /sys/kernel/security/apparmor/profiles > /dev/null 2>&1; then
    APPARMOR="--security-opt apparmor=hassio-supervisor"
else
    APPARMOR="--security-opt apparmor:unconfined"
fi

# Init supervisor
HASSIO_DATA=${DATA}
HASSIO_IMAGE_ID=$(docker inspect --format='{{.Id}}' "${SUPERVISOR}")
HASSIO_CONTAINER_ID=$(docker inspect --format='{{.Image}}' hassio_supervisor || echo "")

runSupervisor() {
    docker rm --force hassio_supervisor || true

    # shellcheck disable=SC2086
    docker run --name hassio_supervisor \
        --privileged \
        $APPARMOR \
        --security-opt seccomp=unconfined \
        -v /run/docker.sock:/run/docker.sock \
        -v /run/dbus:/run/dbus \
        -v /etc/machine-id:/etc/machine-id:ro \
        -v "${HASSIO_DATA}":/data:rw \
        -e SUPERVISOR_SHARE="${HASSIO_DATA}" \
        -e SUPERVISOR_NAME=hassio_supervisor \
        -e SUPERVISOR_MACHINE="${MACHINE}" \
        "${SUPERVISOR}"
}

# Run supervisor
mkdir -p "${HASSIO_DATA}"
([ "${HASSIO_IMAGE_ID}" = "${HASSIO_CONTAINER_ID}" ] && docker start --attach hassio_supervisor) || runSupervisor
